package com.imooc.base;

import org.junit.After;
import org.junit.Before;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;

/**
 * Created by yuzhou on 15-10-24.
 */
public class UnitTestBase {

    public UnitTestBase(){}

    private String springXmlPath;
    private ClassPathXmlApplicationContext context;
    
    public UnitTestBase(String springXmlPath) {
    	this.springXmlPath = springXmlPath;
    }
    
    @Before
    public void before() {
    	if(StringUtils.isEmpty(springXmlPath)) {
    		springXmlPath = "classpath*:spring-*.xml";
    	}
    	try {
			context = new ClassPathXmlApplicationContext(springXmlPath.split("[,\\s]+"));
			context.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    @After
    public void after() {
    	context.destroy();
    }
    
    @SuppressWarnings("unchecked")
	protected <T extends Object> T getBean(String beanId) {
    	try {
			return (T)context.getBean(beanId);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
    }
    
    protected <T extends Object> T getBean(Class<T> clazz) {
    	try {
			return (T)context.getBean(clazz);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
    }
    
}
